/*
 * @Author: LBH 1336709799@qq.com
 * @Date: 2024-11-22 20:44:03
 * @LastEditors: LBH 1336709799@qq.com
 * @LastEditTime: 2024-12-04 15:47:46
 * @FilePath: \vue-admin\src\store\modules\user.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { getProfileAPI, loginAPI } from '@/api/user'
import { TOKEN_KEY } from '@/constants/KEY'
import { getToken, removeToken, setToken } from '@/utils/auth'
import { contantsRoutes } from '@/router'
import { resetRouter } from '@/router'

export default {
  namespaced: true,
  state: () => {
    return {
      // 优先从本地取
      token: getToken() || '',
      profile: {},
      menuList: [...contantsRoutes]
    }
  },
  mutations: {
    setToken(state, token) {
      state.token = token
      // 本地存一份
      setToken(token)
    },
    clearUserInfo(state) {
      // 清除Token
      state.token = ''
      state.profile = {}
      removeToken(TOKEN_KEY)
    },
    setProfile(state, profile) {
      state.profile = profile
    },
    setMenuList(state, filterRoutes) {
      state.menuList = [...state.menuList, ...filterRoutes]
    },
    resetMenu(state) {
      // 重置左侧菜单
      state.menuList = contantsRoutes
      // 重置路由系统
      resetRouter()
    }

  },
  actions: {
    async doLogin(context, { username, password }) {
      // 调用接口
      const res = await loginAPI({ username, password })
      // 提交mutation
      context.commit('setToken', res.data.token)
    },
    async getUserProfile(ctx) {
      const res = await getProfileAPI()
      ctx.commit('setProfile', res.data)
      return res.data.permissions
    }
  }
}
